package dk.modified.reshary;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.Header;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.LruCache;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import dk.modified.reshary.GlobalState.TrackerName;
import dk.modified.reshary.TouchImageView.OnTouchImageViewZoomFinishedListener;

public class ViewShare extends Fragment implements OnTouchListener {

	public ViewShare() {
	}

	private static Boolean emailValidated = null;
	private static Boolean showintro;

	// FINAL VARIABLES
	private static final int SELECT_IMAGE_ACTIVITY_REQUEST_CODE = 1337;
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private static final int REPORT_IMAGE_ACTIVITY_REQUEST_CODE = 13214;
	private static final int SHARE_INTENT_ACTIVITY_REQUEST_CODE = 1234123;
	private static final int SWIPE_MIN_DISTANCE = 175;
	private static final int RESULT_CANCELED = 0;
	private static final int RESULT_OK = -1;
	private float xOnPressed;
	private float yOnPressed;
	private float centerX;
	private float centerY;

	// VIEW ITEM
	private FrameLayout ad_container;
	private ProgressBar progressBar;
	private TouchImageView reshareImage;
	private PopupWindow popupWindow;
	// private Bitmap tempBitmap;
	private ImageView needle;
	private ImageView speedometer;
	private FrameLayout speedometer_container;
	private TextView speedometer_speed;
	private ImageView speedometer_reshare_status;
	private ImageView speedometer_trash_text;
	private ImageView speedometer_reshare_text;
	private LinearLayout speedometer_stage_status_container;
	private LinearLayout speedometer_status_container;
	private View view_background;
	private View popup_shadow;
	private LruCache<String, Bitmap> mMemoryCache;

	private RelativeLayout layout_reshare_slide;
	private RelativeLayout network_retry;
	private FrameLayout image_container;
	private RelativeLayout container_bottom_bar;
	private TextView speedometer_stage_status;
	private ImageButton cmd_report;
	private ImageButton cmd_browse;
	private ImageButton cmd_share;
	private ImageButton cmd_follow;
	private ImageButton cmd_comment;
	private ImageButton cmd_video_play;
	private Button cmd_skip;
	private Button cmd_nomoremedia_goback;
	private MenuItem cameraMenuItem;
	private MenuItem browseMenuItem;
	private static Boolean multiplefingers = false;
	public static Boolean swipeOnImage;
	private static float bytesPrMilli;
	private static Boolean isFollowing = false;
	private long timeOnPress;
	private Uri mImageUri;
	private static int mCategory;
	private Button cmd_network_retry;
	private TextView txt_network_retry;
	private TextView txt_image_title;
	private TextView txt_owner_name;
	private TextView txt_share_number;

	private static int reshare_counter;
	private Boolean wants_bottom_bar_visible = true;
	private Boolean isFavorite = false;
	private static final int AD_UNIT_DISABLED = 0;
	private static final int AD_UNIT_BANNER_ONLY = 1;
	private static final int AD_UNIT_BOTH = 2;
	private AdView adView;
	private InterstitialAd interstitial;
	private AdRequest adRequest;
	private static final String AD_UNIT_ID_BANNER = "ca-app-pub-0994411018581683/5745117723";
	private static final String AD_UNIT_ID_FULLSCREEN = "ca-app-pub-0994411018581683/7221850924";
	private static int adUnitState;
	private static boolean isAdUnitInitial;
	private static Share share;
	private byte[] gifAnimationData;
	private ArrayList<Category> newCategoryArr;
	private Tracker t;
	// private AnimationDrawable gifAnimationData;

	private onCategoryChanged mOnCategoryChanged;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.view_share, container, false);
		Bundle b = getArguments();
		mCategory = b.getInt("cat_id");
		newCategoryArr = b.getParcelableArrayList("categoryArr");
		Log.d("Test", "onCreate()");

		final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

		// Use 1/8th of the available memory for this memory cache.
		final int cacheSize = maxMemory / 8;

		mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap bitmap) {
				// The cache size will be measured in kilobytes rather than
				// number of items.
				return bitmap.getByteCount() / 1024;
			}
		};

		initialize(v);

		if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Configuration newConfig = new Configuration();
			newConfig.orientation = Configuration.ORIENTATION_LANDSCAPE;
			onConfigurationChanged(newConfig);
		}

		reshare_counter = 0;
		adView = new AdView(getActivity().getApplicationContext());
		adView.setAdSize(AdSize.BANNER);
		adView.setAdUnitId(AD_UNIT_ID_BANNER);
		interstitial = new InterstitialAd(getActivity().getApplicationContext());
		interstitial.setAdUnitId(AD_UNIT_ID_FULLSCREEN);

		ad_container.addView(adView);
		adRequest = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
				.addTestDevice("7B8DAADA8F646F0AC8E7C6F08BF2CE05").build();
		isAdUnitInitial = true;
		return v;
	}

	public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
		if (getBitmapFromMemCache(key) == null) {
			mMemoryCache.put(key, bitmap);
		}
	}

	public Bitmap getBitmapFromMemCache(String key) {
		return mMemoryCache.get(key);
	}

	private void initialize(View v) {
		setViews(v);
		setProperties();
		setListeners();
		InitialImageDownload(mCategory);

	}

	private void setViews(View v) {
		ad_container = (FrameLayout) v.findViewById(R.id.ad_container);
		layout_reshare_slide = (RelativeLayout) v
				.findViewById(R.id.layout_reshare_slide);
		txt_image_title = (TextView) v.findViewById(R.id.txt_image_title);
		needle = (ImageView) v.findViewById(R.id.needle);
		popup_shadow = (View) v.findViewById(R.id.popup_shadow);
		view_background = (View) v.findViewById(R.id.view_background);
		speedometer_status_container = (LinearLayout) v
				.findViewById(R.id.speedometer_status_container);
		speedometer_stage_status = (TextView) v
				.findViewById(R.id.speedometer_stage_status);
		speedometer_reshare_status = (ImageView) v
				.findViewById(R.id.speedometer_reshare_status);
		speedometer_container = (FrameLayout) v
				.findViewById(R.id.speedometer_container);
		speedometer = (ImageView) v.findViewById(R.id.speedometer);
		speedometer_speed = (TextView) v.findViewById(R.id.speedometer_speed);
		speedometer_stage_status_container = (LinearLayout) v
				.findViewById(R.id.speedometer_stage_status_container);
		speedometer_trash_text = (ImageView) v
				.findViewById(R.id.speedometer_trash_image);
		speedometer_reshare_text = (ImageView) v
				.findViewById(R.id.speedometer_reshare_image);
		image_container = (FrameLayout) v.findViewById(R.id.image_container);
		container_bottom_bar = (RelativeLayout) v
				.findViewById(R.id.container_bottom_bar);
		progressBar = (ProgressBar) v.findViewById(R.id.prgbar);
		reshareImage = (TouchImageView) v.findViewById(R.id.imgview);
		cmd_report = (ImageButton) v.findViewById(R.id.cmd_report);
		cmd_browse = (ImageButton) v.findViewById(R.id.cmd_browse);
		cmd_share = (ImageButton) v.findViewById(R.id.cmd_share);
		cmd_follow = (ImageButton) v.findViewById(R.id.cmd_follow);
		cmd_comment = (ImageButton) v.findViewById(R.id.cmd_comment);
		cmd_skip = (Button) v.findViewById(R.id.cmd_skip);
		cmd_video_play = (ImageButton) v.findViewById(R.id.cmd_video_play);
		cmd_network_retry = (Button) v.findViewById(R.id.cmd_network_retry);
		network_retry = (RelativeLayout) v.findViewById(R.id.network_retry);
		txt_network_retry = (TextView) v.findViewById(R.id.txt_network_retry);
		txt_owner_name = (TextView) v.findViewById(R.id.txt_owner_name);
		txt_share_number = (TextView) v.findViewById(R.id.txt_share_number);
		cmd_nomoremedia_goback = (Button) v
				.findViewById(R.id.cmd_nomoremedia_goback);
	}

	public void displayInterstitial() {
		if (interstitial.isLoaded()) {
			interstitial.show();
		}
	}

	private void setProperties() {
		share = new Share();
		bytesPrMilli = -1;
		needle.setRotation(90);
		multiplefingers = false;
		swipeOnImage = false;
		setHasOptionsMenu(true);
		progressBar.setVisibility(View.VISIBLE);
		reshareImage.setOnTouchListener(this);
		reshareImage.setVisibility(View.GONE);
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		showintro = sharedpreferences.getBoolean("showintro", true);
		registerForContextMenu(reshareImage);
	}

	private void resetReshareSlidePosition() {
		layout_reshare_slide.setVisibility(View.INVISIBLE);
		view_background.setBackgroundColor(Color.WHITE);
		speedometer_speed.setText(getResources().getString(
				R.string.speedometer_default_speed));
		speedometer_reshare_status.setVisibility(View.VISIBLE);
		speedometer_stage_status.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		speedometer_stage_status_container.setVisibility(View.INVISIBLE);
		speedometer_trash_text.setVisibility(View.GONE);
		speedometer_reshare_text.setVisibility(View.GONE);
		if (share.getVideoFilename() != null) {
			reshareImage.lockZoom(false);
		}
		needle.setRotation(90);
		image_container.setTranslationX(0);
		image_container.clearAnimation();
		swipeOnImage = true;
	}

	private void setTextValue(float rotation) {

		float rotationDegree = rotation + 140;
		final float ratio = 0.91f;
		int red = Math.round(rotationDegree * ratio);
		int blue = Math.round(255 - (rotationDegree * ratio));
		int color = Color.rgb(red, 154, blue);
		view_background.setBackgroundColor(color);
		speedometer_speed.setText(String.valueOf(Math.round(rotationDegree)));

		if (rotation >= -140 && rotation < -112) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_1));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
			speedometer_trash_text.setVisibility(View.VISIBLE);
			speedometer_reshare_text.setVisibility(View.GONE);

		} else if (rotation >= -112 && rotation < -84) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_2));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
			speedometer_trash_text.setVisibility(View.VISIBLE);
			speedometer_reshare_text.setVisibility(View.GONE);

		} else if (rotation >= -84 && rotation < -56) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_3));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 21);
			speedometer_trash_text.setVisibility(View.VISIBLE);
			speedometer_reshare_text.setVisibility(View.GONE);

		} else if (rotation >= -56 && rotation < -28) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_4));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= -28 && rotation < 0) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_5));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 23);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= 0 && rotation < 28) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_6));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= 28 && rotation < 56) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_7));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= 56 && rotation < 84) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_8));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= 84 && rotation < 112) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_9));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 27);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= 112 && rotation < 135) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_10));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		} else if (rotation >= 135) {
			speedometer_stage_status.setText(getResources().getString(
					R.string.speedometer_stage_11));
			speedometer_stage_status
					.setTextSize(TypedValue.COMPLEX_UNIT_SP, 29);
			speedometer_trash_text.setVisibility(View.GONE);
			speedometer_reshare_text.setVisibility(View.VISIBLE);

		}

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			RelativeLayout.LayoutParams layoutParams_speedometer_container = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			layoutParams_speedometer_container
					.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			speedometer_container
					.setLayoutParams(layoutParams_speedometer_container);

			RelativeLayout.LayoutParams layoutParams_status_container = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			layoutParams_status_container
					.addRule(RelativeLayout.CENTER_VERTICAL);
			layoutParams_status_container
					.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			layoutParams_status_container.setMargins(50, 0, 0, 0);
			speedometer_status_container
					.setLayoutParams(layoutParams_status_container);

			FrameLayout.LayoutParams layoutParams_adview = new FrameLayout.LayoutParams(
					FrameLayout.LayoutParams.WRAP_CONTENT,
					FrameLayout.LayoutParams.WRAP_CONTENT);
			layoutParams_adview.gravity = Gravity.TOP | Gravity.LEFT;
			ad_container.setLayoutParams(layoutParams_adview);

		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			RelativeLayout.LayoutParams layoutParams_speedometer_container = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			layoutParams_speedometer_container
					.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
			speedometer_container
					.setLayoutParams(layoutParams_speedometer_container);

			RelativeLayout.LayoutParams layoutParams_status_container = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			layoutParams_status_container
					.addRule(RelativeLayout.CENTER_HORIZONTAL);
			layoutParams_status_container.addRule(RelativeLayout.ABOVE,
					R.id.speedometer_container);
			speedometer_status_container
					.setLayoutParams(layoutParams_status_container);

			FrameLayout.LayoutParams layoutParams_adview = new FrameLayout.LayoutParams(
					FrameLayout.LayoutParams.WRAP_CONTENT,
					FrameLayout.LayoutParams.WRAP_CONTENT);
			layoutParams_adview.gravity = Gravity.TOP | Gravity.CENTER;
			ad_container.setLayoutParams(layoutParams_adview);

		}
	}

	private void setListeners() {

		cmd_nomoremedia_goback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mOnCategoryChanged != null) {
					mOnCategoryChanged.categoryChanged(-1, 0, null);
				}

				// Bundle args = new Bundle();
				// args.putInt("cat_id", -1);
				// Fragment fragment = new ViewShare();
				// fragment.setArguments(args);
				// getActivity().getFragmentManager().beginTransaction()
				// .replace(R.id.content_frame, fragment).commit();

			}
		});

		reshareImage
				.setOnTouchImageViewZoomFinishedListener(new OnTouchImageViewZoomFinishedListener() {

					@Override
					public void ZoomFinished(float normalizedScale) {
						// TODO Auto-generated method stub
						if (normalizedScale == 1f) {
							getActivity().getActionBar().show();
							if (wants_bottom_bar_visible) {
								container_bottom_bar
										.setVisibility(View.VISIBLE);
							}
						}
					}
				});

		cmd_video_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (share.getVideoFilename() != null) {

					if (share.getMediaState() == Share.STATE_VIDEO) {
						Intent i = new Intent(getActivity(),
								VideoActivity.class);
						i.putExtra("videofilename", share.getVideoFilename());
						startActivity(i);
					} else if (share.getMediaState() == Share.STATE_GIF) {
						DownloadGif(share.getVideoFilename());
					}

				} else {
					Toast.makeText(getActivity(),
							getString(R.string.video_unavailable),
							Toast.LENGTH_LONG).show();
				}
			}
		});

		cmd_comment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent startCommentActivity = new Intent(getActivity(),
						CommentActivity.class);
				startCommentActivity.putExtra("mediaid", share.getMediaId());
				startActivity(startCommentActivity);
				getActivity().overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);
			}
		});

		cmd_browse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				stopAnimation();
				Intent intent = new Intent(getActivity()
						.getApplicationContext(), ShowOwnerShares.class);
				intent.putExtra("title", share.getUserName());
				intent.putExtra("ownerid", share.getOwnerId());
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);
			}
		});

		cmd_skip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				resetReshareSlidePosition();
				reshareImage.setVisibility(View.GONE);
				cmd_video_play.setVisibility(View.GONE);
				progressBar.setVisibility(View.VISIBLE);
				InitialImageDownload(mCategory);
			}
		});

		cmd_network_retry.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				progressBar.setVisibility(View.VISIBLE);
				network_retry.setVisibility(View.GONE);
				cmd_nomoremedia_goback.setVisibility(View.GONE);

				if (share.getMediaState() == Share.STATE_GIF) {
					if (share.getVideoFilename() != null) {
						DownloadGif(share.getVideoFilename());
					} else {
						InitialImageDownload(mCategory);
					}
				} else {
					InitialImageDownload(mCategory);
				}

			}
		});

		needle.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					centerX = speedometer.getWidth() / 2;
					centerY = speedometer.getHeight() / 2;

					double angle = Util.getAngleOfLineBetweenTwoPoints(centerX,
							centerY,
							event.getRawX() - speedometer_container.getLeft(),
							event.getRawY() - speedometer_container.getTop()
									- getActivity().getActionBar().getHeight());

					if (angle - 90 < -180) {
						if ((angle + 270) <= 140) {
							needle.setRotation((float) angle);
						}
					} else {
						if ((angle - 90) >= -139) {
							needle.setRotation((float) angle);
						}
					}

					float rotation = needle.getRotation();

					if (rotation != 90) {
						if (rotation - 90 < -180) {
							if ((rotation + 270) <= 140) {
								speedometer_reshare_status
										.setVisibility(View.GONE);
								speedometer_stage_status_container
										.setVisibility(View.VISIBLE);
								setTextValue(rotation + 270);
							}
						} else {
							if (rotation - 90 >= -139) {
								speedometer_reshare_status
										.setVisibility(View.GONE);
								speedometer_stage_status_container
										.setVisibility(View.VISIBLE);
								setTextValue(rotation - 90);
							}
						}

					}

				}
				if (event.getAction() == MotionEvent.ACTION_MOVE) {

					double angle = Util.getAngleOfLineBetweenTwoPoints(centerX,
							centerY,
							event.getRawX() - speedometer_container.getLeft(),
							event.getRawY() - speedometer_container.getTop()
									- getActivity().getActionBar().getHeight());

					if (angle - 90 < -180) {
						if ((angle + 270) <= 140) {
							needle.setRotation((float) angle);
						}
					} else {
						if ((angle - 90) >= -139) {
							needle.setRotation((float) angle);
						}

					}

					float rotation = needle.getRotation();

					if (rotation != 90) {
						if (rotation - 90 < -180) {
							if ((rotation + 270) <= 140) {
								speedometer_reshare_status
										.setVisibility(View.GONE);
								speedometer_stage_status_container
										.setVisibility(View.VISIBLE);
								setTextValue(rotation + 270);
							}
						} else {
							if (rotation - 90 >= -140) {
								speedometer_reshare_status
										.setVisibility(View.GONE);
								speedometer_stage_status_container
										.setVisibility(View.VISIBLE);
								setTextValue(rotation - 90);
							}
						}
					}

				}
				if (event.getAction() == MotionEvent.ACTION_UP) {

					float rotation = needle.getRotation();

					if (rotation != 90) {

						if (rotation - 90 < -180) {
							if ((rotation + 270) <= 140) {
								resetReshareSlidePosition();

								if (showintro) {
									InitialImageDownload(mCategory);
									initiatePopupWindowFinishGuide(getView());
									showintro = false;
									SharedPreferences sharedpreferences = getActivity()
											.getApplicationContext()
											.getSharedPreferences(
													"dk.modified.reshary",
													Context.MODE_PRIVATE);
									Editor editor = sharedpreferences.edit();
									editor.putBoolean("showintro", false);
									editor.commit();
								} else {
									int mediaid = share.getMediaId();
									int numberofreshares = Math
											.round(rotation + 270);
									progressBar.setVisibility(View.VISIBLE);
									reshareImage.setVisibility(View.GONE);
									cmd_video_play.setVisibility(View.GONE);
									ResharePostNDownload(numberofreshares + 5,
											mediaid, mCategory);
								}

							}
						} else {
							if ((rotation - 90) >= -140) {
								resetReshareSlidePosition();

								if (showintro) {
									InitialImageDownload(mCategory);
									initiatePopupWindowFinishGuide(getView());
									showintro = false;
									SharedPreferences sharedpreferences = getActivity()
											.getApplicationContext()
											.getSharedPreferences(
													"dk.modified.reshary",
													Context.MODE_PRIVATE);
									Editor editor = sharedpreferences.edit();
									editor.putBoolean("showintro", false);
									editor.commit();

								} else {
									int mediaid = share.getMediaId();
									int numberofreshares = Math
											.round(rotation - 90);
									progressBar.setVisibility(View.VISIBLE);
									reshareImage.setVisibility(View.GONE);
									cmd_video_play.setVisibility(View.GONE);
									ResharePostNDownload(numberofreshares - 5,
											mediaid, mCategory);

								}

							}

						}
					}

				}

				return true;
			}
		});

		cmd_follow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isFollowing) {
					isFollowing = false;
					UnfollowUserPost(share.getOwnerId());
					cmd_follow
							.setImageResource(R.drawable.ic_action_follow_white);

				} else {
					isFollowing = true;
					FollowUserPost(share.getOwnerId());
					cmd_follow
							.setImageResource(R.drawable.ic_action_unfollow_white);
				}
			}
		});

		cmd_share.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				openSharingIntent();
			}
		});

		cmd_report.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (share.getMediaId() != -1) {
					Intent i = new Intent(getActivity(), ReportActivity.class);
					startActivityForResult(i,
							REPORT_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					Toast.makeText(
							getActivity().getApplicationContext(),
							"Sorry, you can not report when no image is available",
							Toast.LENGTH_LONG).show();
				}
			}
		});

	}

	@Override
	public void onResume() {
		if (adView != null) {
			adView.resume();
		}
		super.onResume();
	}

	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onResume();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		if (popupWindow != null) {
			popupWindow.dismiss();
		}
		super.onDestroy();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.context_menu, menu);
		MenuItem cmd_favorite = menu.findItem(R.id.cmd_favorite);
		if (isFavorite) {
			cmd_favorite.setTitle(getString(R.string.context_favorite_remove));
		} else {
			cmd_favorite.setTitle(getString(R.string.context_favorite_add));
		}
		MenuItem cmd_save = menu.findItem(R.id.cmd_save);
		if (share.getMediaState() == Share.STATE_GIF) {
			cmd_save.setTitle(getString(R.string.save_gif));
		} else {
			cmd_save.setTitle(getString(R.string.save_image));
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		switch (item.getItemId()) {
		case R.id.cmd_favorite:
			if (isFavorite) {
				RemoveFromFavorite(share.getMediaId());
			} else {
				AddToFavorite(share.getMediaId());
			}
			break;
		case R.id.cmd_save:
			if (share.getMediaState() == Share.STATE_GIF) {
				if (gifAnimationData != null) {
					File tempFile = Util.saveGif(gifAnimationData);
					if (tempFile != null) {
						SaveMediaNotification saveNotification = new SaveMediaNotification(
								getActivity(),
								getBitmapFromMemCache(share.getFileName()),
								share.getMediaState(), Uri.fromFile(tempFile));
						saveNotification.createNotification();
					}
				}

				else
					DownloadGifBeforeSave(share.getVideoFilename());
			} else {
				Runnable r = new Runnable() {
					@Override
					public void run() {
						File tempFile = Util
								.saveImage(getBitmapFromMemCache(share
										.getFileName()));
						if (tempFile != null) {
							SaveMediaNotification saveNotification = new SaveMediaNotification(
									getActivity(),
									getBitmapFromMemCache(share.getFileName()),
									share.getMediaState(),
									Uri.fromFile(tempFile));
							saveNotification.createNotification();
						}
					}
				};
				new Thread(r).start();

			}
			break;
		default:
			return super.onContextItemSelected(item);
		}

		return true;
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		MenuItem browse = menu.findItem(R.id.action_browse);
		this.browseMenuItem = browse;
		MenuItem camera = menu.findItem(R.id.action_camera);
		this.cameraMenuItem = camera;
		if (emailValidated == null) {
			browse.setEnabled(false);
			camera.setEnabled(false);
		}
		super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		inflater.inflate(R.menu.main, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REPORT_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String issue = data.getExtras().getString("issue");
				String text = data.getExtras().getString("reason");
				String mediaid = String.valueOf(share.getMediaId());
				ReportMedia(mediaid, issue, text);
				resetReshareSlidePosition();
				reshareImage.setVisibility(View.GONE);
				cmd_video_play.setVisibility(View.GONE);
				progressBar.setVisibility(View.VISIBLE);
				InitialImageDownload(mCategory);
			}
		}

		if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {

				Intent i = new Intent(getActivity(), UploadActivity.class);
				i.setType("image/*");
				i.putExtra("imageUri", mImageUri);
				i.putParcelableArrayListExtra("categoryArr", newCategoryArr);
				startActivity(i);
				getActivity().overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);

			} else if (resultCode == RESULT_CANCELED) {
			} else {

			}
		}
		if (requestCode == SELECT_IMAGE_ACTIVITY_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {

				Intent i = new Intent(getActivity(), UploadActivity.class);
				i.setType("image/*");
				i.putExtra("imageUri", data.getData());
				i.putParcelableArrayListExtra("categoryArr", newCategoryArr);
				startActivity(i);
				getActivity().overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);

			} else if (resultCode == RESULT_CANCELED) {
			} else {
			}
		}

		if (requestCode == SHARE_INTENT_ACTIVITY_REQUEST_CODE) {
			Log.d("RESULTCODE", resultCode + "");
			Log.d("DATA", (data != null) + "");
			if (resultCode == RESULT_OK) {

			} else if (resultCode == RESULT_CANCELED) {

			}
		}
	}

	public int[] getScreenSize() {
		DisplayMetrics metrics = this.getResources().getDisplayMetrics();
		int width = metrics.widthPixels;
		int height = metrics.heightPixels;

		int[] arr = new int[2];
		arr[0] = width;
		arr[1] = height;
		return arr;
	}

	private void openSharingIntent() {
		Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
				"Reshary image");
		String shareMessage = getResources().getString(
				R.string.share_media_text)
				+ " " + share.getSharingUrl();
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);

		startActivityForResult(Intent.createChooser(sharingIntent, "Share"),
				SHARE_INTENT_ACTIVITY_REQUEST_CODE);
	}

	private void startCaptureImageIntent() {

		if (doesDeviceSupportCamera()) {

			File photo = null;
			try {
				photo = this.createTemporaryFile("Reshary-", ".jpg");
			} catch (Exception e) {
				Log.v("DEBUG CAMERA", "Can't create file to take picture!");
				Toast.makeText(getActivity(),
						"Please check SD card! Image shot is impossible!",
						Toast.LENGTH_LONG).show();
			}
			stopAnimation();
			mImageUri = Uri.fromFile(photo);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
			startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

		} else {
			Toast.makeText(getActivity(),
					"Sorry, your device does not support Camera",
					Toast.LENGTH_LONG).show();
		}

	}

	private void startBrowseImageIntent() {
		stopAnimation();
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				SELECT_IMAGE_ACTIVITY_REQUEST_CODE);
	}

	private boolean doesDeviceSupportCamera() {

		PackageManager pm = getActivity().getApplicationContext()
				.getPackageManager();
		if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
				|| pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
				|| pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
			// this device has a camera
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

	private File createTemporaryFile(String part, String ext) throws Exception {
		File tempDir = Environment.getExternalStorageDirectory();
		tempDir = new File(tempDir.getAbsolutePath() + "/Reshary/");
		if (!tempDir.exists()) {
			tempDir.mkdir();
		}
		return File.createTempFile(part, ext, tempDir);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.

		int id = item.getItemId();
		if (id == R.id.action_user_shares) {

			SharedPreferences sharedpreferences = getActivity()
					.getSharedPreferences("dk.modified.reshary",
							Context.MODE_PRIVATE);
			String userId = sharedpreferences.getString("userid", "");

			if (!userId.equals("")) {
				Intent intent = new Intent(getActivity()
						.getApplicationContext(), ShowOwnerShares.class);
				intent.putExtra("title", getString(R.string.action_user_shares));
				intent.putExtra("ownerid", userId);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);
			} else {
				Toast.makeText(
						getActivity(),
						getResources().getString(
								R.string.network_try_again_text),
						Toast.LENGTH_LONG).show();
			}

			return true;
		}
		if (id == R.id.action_favorites) {

			SharedPreferences sharedpreferences = getActivity()
					.getSharedPreferences("dk.modified.reshary",
							Context.MODE_PRIVATE);
			String userId = sharedpreferences.getString("userid", "");

			if (!userId.equals("")) {
				Intent intent = new Intent(getActivity()
						.getApplicationContext(), ShowOwnerShares.class);
				intent.putExtra("title", getString(R.string.favorite_title));
				intent.putExtra("ownerid", userId);
				intent.putExtra("favorite", true);
				startActivity(intent);
				getActivity().overridePendingTransition(R.anim.fadeout,
						R.anim.fadein);
			} else {
				Toast.makeText(
						getActivity(),
						getResources().getString(
								R.string.network_try_again_text),
						Toast.LENGTH_LONG).show();
			}

			return true;
		}
		if (id == R.id.action_camera) {
			if (emailValidated == true) {
				startCaptureImageIntent();
			} else {
				popup_shadow.setVisibility(View.VISIBLE);
				initiatePopupWindowVerifyEmail(getView());
			}

			return true;
		}
		if (id == R.id.action_browse) {
			if (emailValidated == true) {
				startBrowseImageIntent();
			} else {
				popup_shadow.setVisibility(View.VISIBLE);
				initiatePopupWindowVerifyEmail(getView());
			}
			return true;
		}
		if (id == R.id.action_settings) {

			SharedPreferences sharedpreferences = getActivity()
					.getSharedPreferences("dk.modified.reshary",
							Context.MODE_PRIVATE);
			String securitytoken = sharedpreferences.getString("securitytoken",
					"");
			String base64token = Base64.encodeToString(
					securitytoken.getBytes(), Base64.DEFAULT);

			String userId = sharedpreferences.getString("userid", "");

			String getSettingsUrl = getString(R.string.app_domain)
					+ "/app_access/settings/?userid=" + userId
					+ "&securitytoken=" + base64token;

			Intent browserIntent = new Intent(getActivity(),
					WebviewActivity.class);
			browserIntent.putExtra("url", getSettingsUrl);
			startActivity(browserIntent);
			getActivity().overridePendingTransition(R.anim.fadeout,
					R.anim.fadein);
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		if (reshareImage.getCurrentZoom() > 1) {
			container_bottom_bar.setVisibility(View.GONE);

			getActivity().getActionBar().hide();
			return true;

		} else if (reshareImage.getCurrentZoom() < 1
				|| layout_reshare_slide.isShown()) {
			return true;
		} else {
			getActivity().getActionBar().show();
			if (wants_bottom_bar_visible) {
				container_bottom_bar.setVisibility(View.VISIBLE);
			}

			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				xOnPressed = event.getRawX();
				yOnPressed = event.getRawY();
			}

			if (event.getAction() == MotionEvent.ACTION_MOVE && swipeOnImage) {

				float differenceX = Util.calculateDifference(xOnPressed,
						event.getRawX());

				if (event.getPointerCount() > 1) {
					multiplefingers = true;
				}

				if (event.getPointerCount() == 1
						&& event.getRawX() < xOnPressed) {

					image_container
							.setTranslationX((event.getRawX() - xOnPressed));

					if (SWIPE_MIN_DISTANCE >= Math.abs(event.getRawX()
							- xOnPressed)) {
						if (differenceX <= SWIPE_MIN_DISTANCE) {

						}
					}
				}

			}

			if (event.getAction() == MotionEvent.ACTION_UP && swipeOnImage) {
				if (!multiplefingers) {

					float transformDistance = Util.calculateDifference(
							event.getRawX(), xOnPressed);
					final int animationDuration = 200;

					if (SWIPE_MIN_DISTANCE <= transformDistance) {

						// ANIMATION SLIDE POSITION

						int width = (int) (getScreenSize()[0] * 0.60);
						float translateWidth = width
								- Math.abs(image_container.getTranslationX());

						if (xOnPressed - event.getRawX() > 0) {

							TranslateAnimation translateanimation = new TranslateAnimation(
									0, Util.oppositeValue(translateWidth),
									0.0f, 0.0f);
							translateanimation
									.setAnimationListener(new TranslateAnimation.AnimationListener() {

										@Override
										public void onAnimationStart(
												Animation animation) {

										}

										@Override
										public void onAnimationEnd(
												Animation animation) {

											if (popupWindow != null) {
												popupWindow.dismiss();
											}
											if (showintro) {
												initiatePopupWindowInitialSpeedometerGuide(getView());
											}

											layout_reshare_slide
													.setVisibility(View.VISIBLE);
											reshareImage.lockZoom(true);
											if (share.getMediaState() == Share.STATE_GIF) {
												if (reshareImage.isAnimating()) {
													// reshareImage
													// .setImageBitmap(tempBitmap);
													reshareImage
															.setImageBitmap(getBitmapFromMemCache(share
																	.getFileName()));

													reshareImage.clear();
													cmd_video_play
															.setVisibility(View.VISIBLE);
												}
											}
										}

										@Override
										public void onAnimationRepeat(
												Animation animation) {

										}

									});
							translateanimation.setDuration(animationDuration); // animation
							// duration

							AlphaAnimation alphaanimation = new AlphaAnimation(
									1.0f, 0.4f);
							alphaanimation.setDuration(animationDuration);

							AnimationSet animationset = new AnimationSet(true);
							animationset.addAnimation(translateanimation);
							animationset.addAnimation(alphaanimation);
							animationset.setFillAfter(true);
							animationset.setFillEnabled(true);

							image_container.startAnimation(animationset);
						}
					} else {

						image_container.setTranslationX(0);
						image_container.clearAnimation();
					}
				} else {

					image_container.setTranslationX(0);
					image_container.clearAnimation();

				}
				multiplefingers = false;
			}

		}

		if (share.getMediaId() != -1) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				timeOnPress = System.currentTimeMillis();
			}

			if (event.getAction() == MotionEvent.ACTION_UP) {

				long diff = System.currentTimeMillis() - timeOnPress;
				if (diff < 300 && event.getPointerCount() == 1) {

					if (Util.calculateDifference(xOnPressed, event.getRawX()) < 10
							|| Util.calculateDifference(yOnPressed,
									event.getRawY()) < 10) {

						if (share.getMediaState() == Share.STATE_GIF) {
							if (reshareImage.isAnimating()) {

								reshareImage
										.setImageBitmap(getBitmapFromMemCache(share
												.getFileName()));
								// if(tempBitmap != null &&
								// tempBitmap.isRecycled()){
								// tempBitmap =
								// getBitmapFromMemCache(share.getFileName());
								// reshareImage.setImageBitmap(tempBitmap);
								// }else {
								// reshareImage.setImageBitmap(tempBitmap);
								// }
								reshareImage.clear();
								cmd_video_play.setVisibility(View.VISIBLE);
							} else {
								setBottomBarVisibility(event);
							}
						} else {
							setBottomBarVisibility(event);
						}

					}
				}

			}

		}

		return true;
	}

	private void setBottomBarVisibility(MotionEvent event) {
		if (container_bottom_bar.isShown()) {
			if (event.getAxisValue(MotionEvent.AXIS_Y) < container_bottom_bar
					.getTop()) {

				wants_bottom_bar_visible = false;
				container_bottom_bar.setVisibility(View.GONE);
			}
		} else {
			container_bottom_bar.setVisibility(View.VISIBLE);
			wants_bottom_bar_visible = true;
		}
	}

	private void initiatePopupWindowInitialSpeedometerGuide(View v) {
		try {
			LayoutInflater inflater = (LayoutInflater) getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View layout = inflater.inflate(
					R.layout.popup_guide_speedometer_initial,
					(ViewGroup) v.findViewById(R.id.popup_speedometer_initial));
			popupWindow = new PopupWindow(layout,
					ViewGroup.LayoutParams.MATCH_PARENT,
					(int) TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 210, this
									.getResources().getDisplayMetrics()), true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.setOutsideTouchable(true);
			popupWindow.setTouchable(true);
			popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);
			layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					popupWindow.dismiss();
				}
			});
			popupWindow
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							popupWindow.dismiss();
							popupWindow = null;
							initiatePopupWindowSpeedometerGuide(getView());
							popup_shadow.setVisibility(View.GONE);
						}
					});
		} catch (Exception e) {
			e.getMessage();
		}
	}

	private void initiatePopupWindowSpeedometerGuide(View v) {
		try {
			LayoutInflater inflater = (LayoutInflater) getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View layout = inflater.inflate(
					R.layout.popup_guide_speedometer,
					(ViewGroup) v.findViewById(R.id.popup_speedometer));
			popupWindow = new PopupWindow(layout,
					ViewGroup.LayoutParams.MATCH_PARENT,
					(int) TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 210, this
									.getResources().getDisplayMetrics()), true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.setOutsideTouchable(true);
			popupWindow.setTouchable(false);
			popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);
			popupWindow
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							popupWindow.dismiss();
							popupWindow = null;
							popup_shadow.setVisibility(View.GONE);
						}
					});
		} catch (Exception e) {
			e.getMessage();
		}

	}

	private void initiatePopupWindowIntroGuide(View v) {
		try {
			LayoutInflater inflater = (LayoutInflater) getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View layout = inflater.inflate(R.layout.popup_intro_guide,
					(ViewGroup) v.findViewById(R.id.popup_guide_intro));
			popupWindow = new PopupWindow(layout,
					ViewGroup.LayoutParams.MATCH_PARENT,
					(int) TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 210, this
									.getResources().getDisplayMetrics()), true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.setOutsideTouchable(false);
			popupWindow.setTouchable(false);
			final ImageView image_swipe_left = (ImageView) layout
					.findViewById(R.id.image_swipe_left);

			final TranslateAnimation img_animation = new TranslateAnimation(
					0.0f, -200.0f, 0.0f, 0.0f);
			img_animation.setDuration(1500);
			img_animation.setRepeatCount(1);
			img_animation.setRepeatMode(Animation.REVERSE);
			final Handler handler = new Handler();
			final Runnable r = new Runnable() {

				@Override
				public void run() {
					image_swipe_left.startAnimation(img_animation);
				}
			};
			img_animation.setAnimationListener(new AnimationListener() {

				@Override
				public void onAnimationStart(Animation animation) {

				}

				@Override
				public void onAnimationRepeat(Animation animation) {

				}

				@Override
				public void onAnimationEnd(Animation animation) {
					handler.postDelayed(r, 2000);
				}
			});

			image_swipe_left.startAnimation(img_animation);

			popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);

			popupWindow
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							popupWindow.dismiss();
							popupWindow = null;
							handler.removeCallbacks(r);
							image_swipe_left.clearAnimation();
							popup_shadow.setVisibility(View.GONE);
						}
					});
		} catch (Exception e) {
			e.getMessage();
		}

	}

	private void initiatePopupWindowFinishGuide(View v) {
		try {
			LayoutInflater inflater = (LayoutInflater) getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View layout = inflater.inflate(R.layout.popup_finish_guide,
					(ViewGroup) v.findViewById(R.id.popup_finish));
			popupWindow = new PopupWindow(layout,
					ViewGroup.LayoutParams.MATCH_PARENT,
					(int) TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 210, this
									.getResources().getDisplayMetrics()), true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.setOutsideTouchable(true);
			popupWindow.setTouchable(true);
			popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);
			layout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					popupWindow.dismiss();
				}
			});
			popupWindow
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							popupWindow.dismiss();
							popupWindow = null;
							popup_shadow.setVisibility(View.GONE);
						}
					});
		} catch (Exception e) {
			e.getMessage();
		}
	}

	@SuppressWarnings("deprecation")
	private void initiatePopupWindowVerifyEmail(View v) {
		try {
			// We need to get the instance of the LayoutInflater
			LayoutInflater inflater = (LayoutInflater) getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.post_popup,
					(ViewGroup) v.findViewById(R.id.popup_element));
			popupWindow = new PopupWindow(layout,
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT, true);
			popupWindow.setBackgroundDrawable(new BitmapDrawable());
			popupWindow.setOutsideTouchable(true);
			TextView txt_title = (TextView) layout.findViewById(R.id.txt_title);
			String text = getResources().getString(R.string.resend_validation);
			txt_title.setText(text);
			popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 0);

			popupWindow
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							popupWindow.dismiss();
							popupWindow = null;
							popup_shadow.setVisibility(View.GONE);
						}
					});

			Button btn_send_popup = (Button) layout
					.findViewById(R.id.btn_ok_popup);
			final EditText txt_email = (EditText) layout
					.findViewById(R.id.txt_email);

			SharedPreferences sharedpreferences = getActivity()
					.getSharedPreferences("dk.modified.reshary",
							Context.MODE_PRIVATE);
			String email = sharedpreferences.getString("email", "");
			txt_email.setText(email);
			txt_email.setKeyListener(null);

			// onClick Listeners

			btn_send_popup.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String text = txt_email.getText().toString();
					ResendEmailConfirmation(getActivity(), text);
					// DO STUFF
					popupWindow.dismiss();
					popupWindow = null;

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void noMoreMedia(int category) {
		txt_network_retry.setText(getResources().getString(
				R.string.message_no_more_media));
		browseMenuItem.setEnabled(true);
		cameraMenuItem.setEnabled(true);

		swipeOnImage = false;
		container_bottom_bar.setVisibility(View.GONE);
		reshareImage.setVisibility(View.GONE);
		reshareImage.clear();
		gifAnimationData = null;
		cmd_video_play.setVisibility(View.GONE);
		progressBar.setVisibility(View.GONE);
		network_retry.setVisibility(View.VISIBLE);
		share.setVideoFilename(null);
		share.setMediaState(Share.STATE_IMAGE);
		if (category != -1) {
			cmd_network_retry.setVisibility(View.GONE);
			cmd_nomoremedia_goback.setVisibility(View.VISIBLE);
			txt_network_retry.setText(getResources().getString(
					R.string.message_no_more_media_category));
		} else {
			txt_network_retry.setText(getResources().getString(
					R.string.message_no_more_media));
			cmd_network_retry.setVisibility(View.VISIBLE);
		}
		share.setMediaId(-1);

	}

	private void networkError() {
		txt_network_retry.setText(getResources().getString(
				R.string.network_try_again_text));

		swipeOnImage = false;
		share.setMediaId(-1);
		cmd_video_play.setVisibility(View.GONE);
		reshareImage.setVisibility(View.GONE);
		reshareImage.clear();
		gifAnimationData = null;
		progressBar.setVisibility(View.GONE);
		network_retry.setVisibility(View.VISIBLE);
		container_bottom_bar.setVisibility(View.GONE);
	}

	public void AddToFavorite(int mediaId) {
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("add_favorite/", params,
				new AsyncHttpResponseHandler() {
					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						isFavorite = false;
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.favorite_add);
						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						isFavorite = true;
					}

				}, getActivity());

	}

	public void RemoveFromFavorite(int mediaId) {
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("rem_favorite/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						isFavorite = true;
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.favorite_remove);
						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						isFavorite = false;
					}

				}, getActivity());

	}

	public void FollowUserPost(String ownerid) {
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("ownerid", ownerid);

		ResharyRestClient.post("follow/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						isFollowing = false;
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.following);
						Toast.makeText(getActivity(),
								text + " " + share.getUserName(),
								Toast.LENGTH_LONG).show();
						isFollowing = true;
					}

				}, getActivity());

	}

	public void UnfollowUserPost(String ownerid) {
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("ownerid", ownerid);

		ResharyRestClient.post("unfollow/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);

						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						isFollowing = true;
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						String text = getResources().getString(
								R.string.no_longer_following);
						Toast.makeText(getActivity(),
								text + " " + share.getUserName(),
								Toast.LENGTH_LONG).show();
						isFollowing = false;
					}

				}, getActivity());

	}

	private void ReportMedia(String mediaid, String issue, String reporttext) {

		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("reason", reporttext);
		params.put("issue", issue);
		params.put("mediaid", String.valueOf(mediaid));

		ResharyRestClient.post("reportit/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						// TODO
						Log.d("TEST", arg3.getMessage().toString());
						super.onFailure(arg0, arg1, arg2, arg3);
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						super.onSuccess(arg0, arg1, arg2);
						String toastText = getResources().getString(
								R.string.report_success);
						Toast.makeText(getActivity(), toastText,
								Toast.LENGTH_LONG).show();
					}

				}, getActivity());

	}

	public void ResharePostNDownload(int limit, int mediaid, int category) {

		reshareImage.clear();
		gifAnimationData = null;

		int[] screenSize = getScreenSize();
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("shares", String.valueOf(limit));
		params.put("mediaid", String.valueOf(mediaid));
		params.put("width", String.valueOf(screenSize[0]));
		params.put("height", String.valueOf(screenSize[1]));
		if (bytesPrMilli != -1) {
			params.put("speed", String.valueOf(bytesPrMilli));
		}
		if (category != -1) {
			params.put("category", String.valueOf(category));
		}

		ResharyRestClient.post("reshareit/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						networkError();
					}

					@Override
					public void onSuccess(String response) {
						Map<String, String> keyvalueResponse = Util
								.newformatResponse(response);
						reshare_counter++;
						moveAd(reshare_counter);
						if (keyvalueResponse.containsKey("showadds")) {
							adUnitState = Integer.parseInt(keyvalueResponse
									.get("showadds"));
						}

						if (!ViewShareController
								.isUsertokenValid(keyvalueResponse))
							Util.intentSendBackUser(getActivity());

						if (!ViewShareController.isError(keyvalueResponse))
							if (ViewShareController
									.isFilenameSet(keyvalueResponse)) {
								// TODO
								DownloadImage(keyvalueResponse);

							} else
								noMoreMedia(mCategory);
						else
							noMoreMedia(mCategory);

						if (ViewShareController
								.isMailApproved(keyvalueResponse))
							emailValidated = true;
						else
							emailValidated = false;
					}

				}, getActivity());

	}

	private void moveAd(int reshare_count) {
		if (reshare_count >= 5) {

			reshare_counter = 0;
		}
	}

	public void InitialImageDownload(int category) {
		reshareImage.clear();
		gifAnimationData = null;

		int[] screenSize = getScreenSize();
		SharedPreferences sharedpreferences = getActivity()
				.getSharedPreferences("dk.modified.reshary",
						Context.MODE_PRIVATE);
		String userid = sharedpreferences.getString("userid", "null");
		String securitytoken = sharedpreferences.getString("securitytoken",
				"null");

		RequestParams params = new RequestParams();
		params.put("userid", userid);
		params.put("securitytoken", securitytoken);
		params.put("width", String.valueOf(screenSize[0]));
		params.put("height", String.valueOf(screenSize[1]));
		if (bytesPrMilli != -1) {
			params.put("speed", String.valueOf(bytesPrMilli));
		}
		if (category != -1) {
			params.put("category", String.valueOf(category));
		}

		ResharyRestClient.post("requestnewmedia/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						networkError();
					}

					@Override
					public void onSuccess(String response) {

						Map<String, String> keyvalueResponse = Util
								.newformatResponse(response);

						if (keyvalueResponse.containsKey("showadds")) {
							adUnitState = Integer.parseInt(keyvalueResponse
									.get("showadds"));
						}

						if (!ViewShareController
								.isUsertokenValid(keyvalueResponse))
							Util.intentSendBackUser(getActivity());

						if (!ViewShareController.isError(keyvalueResponse))
							if (ViewShareController
									.isFilenameSet(keyvalueResponse)) {
								DownloadImage(keyvalueResponse);
							}

							else
								noMoreMedia(mCategory);
						else
							noMoreMedia(mCategory);

						if (ViewShareController
								.isMailApproved(keyvalueResponse))
							emailValidated = true;
						else
							emailValidated = false;
					}

				}, getActivity());
	}

	private void setShare(Map<String, String> response) {
		share.setMediaId(Integer.parseInt(response.get("mediaid")));
		share.setUserName(response.get("realname"));
		share.setFileName(response.get("filename"));
		share.setSharingUrl(response.get("sharingurl"));
		share.setOwnerId(response.get("owner"));
		share.setTitle(response.get("mediatitle"));
		share.setShares(response.get("shares"));
		share.setMediaState(Integer.parseInt(response.get("mediatype")));
	}

	public void DownloadImage(final Map<String, String> response) {
		Log.d("RESPONSE", response.toString());
		gifAnimationData = null;

		final long executionTime = System.currentTimeMillis();

		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };
		ResharyRestClient.downloadImage(response.get("filename"), null,
				new BinaryHttpResponseHandler(allowedContentTypes) {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {
						bytesPrMilli = -1;
						if (statusCode == 404) {
							progressBar.setVisibility(View.VISIBLE);
							network_retry.setVisibility(View.GONE);
							cmd_nomoremedia_goback.setVisibility(View.GONE);
							InitialImageDownload(mCategory);
						} else {
							networkError();
						}
					}

					@Override
					public void onSuccess(byte[] binaryData) {
						long downloadTime = System.currentTimeMillis()
								- executionTime;
						Bitmap tempBitmap = BitmapFactory.decodeByteArray(
								binaryData, 0, binaryData.length);

						int byteSize = byteSizeOf(tempBitmap);

						bytesPrMilli = byteSize / downloadTime;

						if (response.containsKey("mediaid")) {
							setShare(response);
						}

						switch (share.getMediaState()) {

						case Share.STATE_IMAGE:

							t = ((GlobalState) getActivity().getApplication())
									.getTracker(TrackerName.APP_TRACKER);
							t.setScreenName("Reshary Media Image");
							t.send(new HitBuilders.AppViewBuilder().build());

							reshareImage.setImageBitmap(tempBitmap);
							cmd_video_play.setVisibility(View.GONE);
							share.setVideoFilename(null);
							reshareImage.lockZoom(false);
							break;

						case Share.STATE_VIDEO:

							t = ((GlobalState) getActivity().getApplication())
									.getTracker(TrackerName.APP_TRACKER);
							t.setScreenName("Reshary Media Video");
							t.send(new HitBuilders.AppViewBuilder().build());

							reshareImage.setImageBitmap(tempBitmap);
							cmd_video_play.setVisibility(View.VISIBLE);
							share.setVideoFilename(response.get("streamurl"));
							reshareImage.lockZoom(true);
							break;

						case Share.STATE_GIF:

							t = ((GlobalState) getActivity().getApplication())
									.getTracker(TrackerName.APP_TRACKER);
							t.setScreenName("Reshary Media GIF");
							t.send(new HitBuilders.AppViewBuilder().build());

							reshareImage.setImageBitmap(tempBitmap);
							cmd_video_play.setVisibility(View.VISIBLE);
							share.setVideoFilename(response.get("streamurl"));
							reshareImage.lockZoom(true);
							break;

						default:
							reshareImage.setImageBitmap(tempBitmap);
							cmd_video_play.setVisibility(View.GONE);
							share.setVideoFilename(null);
							reshareImage.lockZoom(false);
							break;

						}

						progressBar.setVisibility(View.GONE);
						reshareImage.setVisibility(View.VISIBLE);

						addBitmapToMemoryCache(share.getFileName(), tempBitmap);

						browseMenuItem.setEnabled(true);
						cameraMenuItem.setEnabled(true);
						if (response.containsKey("followerid")) {
							if (response.get("followerid").equals("0")) {
								isFollowing = false;
								cmd_follow
										.setImageResource(R.drawable.ic_action_follow_white);
							} else {
								isFollowing = true;
								cmd_follow
										.setImageResource(R.drawable.ic_action_unfollow_white);
							}

						}

						isFavorite = false;
						txt_image_title.setText(share.getTitle());
						txt_owner_name.setText(share.getUserName());
						txt_share_number.setText(share.getShares());

						if (wants_bottom_bar_visible) {
							container_bottom_bar.setVisibility(View.VISIBLE);
						}

						swipeOnImage = true;

						// Start loading the ad in the background.
						if (isAdUnitInitial) {
							if (adUnitState == AD_UNIT_BANNER_ONLY) {
								adView.loadAd(adRequest);
							} else if (adUnitState == AD_UNIT_BOTH) {
								interstitial.loadAd(adRequest);
								adView.loadAd(adRequest);
							}
							isAdUnitInitial = false;
						} else {
							if (adUnitState == AD_UNIT_BOTH) {
								interstitial.loadAd(adRequest);
							}
						}

						displayInterstitial();

						if (showintro) {
							initiatePopupWindowIntroGuide(getView());
						}
					}

				}, getActivity(), response);
	}

	private void DownloadGif(String filename) {

		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		cmd_video_play.setVisibility(View.GONE);
		if (gifAnimationData != null) {
			reshareImage.setBytes(gifAnimationData);
			reshareImage.startAnimation();
		}

		else {
			reshareImage.setVisibility(View.GONE);
			progressBar.setVisibility(View.VISIBLE);

			ResharyRestClient.downloadImage(filename, null,
					new BinaryHttpResponseHandler(allowedContentTypes) {

						@Override
						public void onFailure(int statusCode, Header[] headers,
								byte[] binaryData, Throwable error) {
							bytesPrMilli = -1;
							if (statusCode == 404) {
								Toast.makeText(
										getActivity().getApplicationContext(),
										getString(R.string.file_not_found_404),
										Toast.LENGTH_LONG).show();
								progressBar.setVisibility(View.GONE);
								reshareImage.setVisibility(View.VISIBLE);
								cmd_video_play.setVisibility(View.VISIBLE);

							} else {
								networkError();
							}
						}

						@Override
						public void onSuccess(byte[] binaryData) {

							try{
								gifAnimationData = binaryData;

								reshareImage.startAnimation();
								reshareImage.setBytes(binaryData);

								progressBar.setVisibility(View.GONE);
								reshareImage.setVisibility(View.VISIBLE);
								swipeOnImage = true;
							} catch(Exception e){
								Toast.makeText(getActivity(), getString(R.string.gif_error), Toast.LENGTH_LONG).show();
								progressBar.setVisibility(View.GONE);
								reshareImage.setVisibility(View.VISIBLE);
								swipeOnImage = true;
								reshareImage.clearAnimation();
								gifAnimationData = null;
							}
						}

					}, getActivity(), null);

		}

	}

	private void DownloadGifBeforeSave(String filename) {
		
		final DownloadNotification notificationDownload = new DownloadNotification(getActivity());
		notificationDownload.createNotification();

		String[] allowedContentTypes = new String[] { "image/jpeg",
				"image/png", "image/gif", "application/octet-stream",
				"text/html" };

		ResharyRestClient.downloadImage(filename, null,
				new BinaryHttpResponseHandler(allowedContentTypes) {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] binaryData, Throwable error) {
						bytesPrMilli = -1;
						Toast.makeText(getActivity().getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onProgress(int bytesWritten, int totalSize) {
					    int progressPercentage = (int)100*bytesWritten/totalSize;
					    if(progressPercentage % 5 == 0)
					    notificationDownload.setProgress(progressPercentage);
					}

					@Override
					public void onSuccess(byte[] binaryData) {
						notificationDownload.completed();
						try {
							gifAnimationData = binaryData;
							File tempFile = Util.saveGif(gifAnimationData);
							if (tempFile != null) {
								SaveMediaNotification saveNotification = new SaveMediaNotification(
										getActivity(), getBitmapFromMemCache(share
												.getFileName()), share
												.getMediaState(), Uri
												.fromFile(tempFile));
								saveNotification.createNotification();
							}
						} catch (Exception e){
							Toast.makeText(getActivity(), getString(R.string.gif_error), Toast.LENGTH_LONG).show();
						}

					}

				}, getActivity(), null);

	}

	/**
	 * returns the bytesize of the give bitmap
	 */
	@TargetApi(Build.VERSION_CODES.KITKAT)
	public static int byteSizeOf(Bitmap bitmap) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			return bitmap.getAllocationByteCount();
		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
			return bitmap.getByteCount();
		} else {
			return bitmap.getRowBytes() * bitmap.getHeight();
		}
	}

	public void ResendEmailConfirmation(Context c, String email) {
		RequestParams params = new RequestParams();
		params.put("email", email);

		ResharyRestClient.post("resend_validation/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						String text = getResources().getString(
								R.string.network_error);
						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						;
					}

					@Override
					public void onSuccess(String content) {
						String text = getResources().getString(
								R.string.email_sent);
						Toast.makeText(getActivity(), text, Toast.LENGTH_LONG)
								.show();
						;
					}

				}, c);
	}

	public void setOnCategoryChangedListener(onCategoryChanged listener) {
		mOnCategoryChanged = listener;
	}

	interface onCategoryChanged {
		public void categoryChanged(int pos, int categoryId, String categoryName);
	}

	private void stopAnimation() {
		if (reshareImage.isAnimating()) {
			// if(tempBitmap != null && tempBitmap.isRecycled()){
			// tempBitmap = getBitmapFromMemCache(share.getFileName());
			// reshareImage.setImageBitmap(tempBitmap);
			// }else {
			// reshareImage.setImageBitmap(tempBitmap);
			// }
			reshareImage.setImageBitmap(getBitmapFromMemCache(share
					.getFileName()));

			// reshareImage.setImageBitmap(getBitmapFromMemCache(share.getFileName()));
			//
			reshareImage.clear();
			if (share != null) {
				if (share.getMediaState() == Share.STATE_GIF) {
					if (cmd_video_play != null) {
						cmd_video_play.setVisibility(View.VISIBLE);
					}
				}
			}
		}
	}

}
